package day10.homework;

import java.beans.beancontext.BeanContext;
import java.util.*;

//有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池用一个数组int[] arr = {10,5,20,50,100,200,500,800,2,80,300};
//创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”，“抽奖箱2”，随机从arr数组中获取奖项元素并打印在控制台上,格式如下:
//抽奖箱1 又产生了一个 10 元大奖
//抽奖箱2 又产生了一个 100 元大奖
public class LotteryDraw {
    public static void main(String[] args) {
        //原始奖项数组
        int[] arr = {10, 5, 20, 50, 100, 200, 500, 800, 2, 80, 300};
        //转换为List<Integer>
        List<Integer> prizes = new ArrayList<>();
        for (int num : arr) {
            prizes.add(num);
        }
        // 打乱奖项顺序
        Collections.shuffle(prizes);
        // 创建共享的抽奖任务
        Prize p = new Prize(prizes);
        Thread t1 = new Thread(p, "抽奖箱1");
        Thread t2 = new Thread(p, "抽奖箱2");
        t1.start();
        t2.start();
    }
}
class Prize implements Runnable{
    List<Integer> prizes;
    Random random = new Random();

    public Prize(List<Integer> prizes) {
        this.prizes = prizes;
    }

    public void run() {
        String name = Thread.currentThread().getName();
        while (true) {
            synchronized (this) {
                // 检查奖池是否为空
                if (prizes.isEmpty()) {
                    System.out.println(name + "奖池已空，停止抽奖");
                    break;
                }
                int index = random.nextInt(prizes.size());
                int prize = prizes.remove(index);
                System.out.println(name + " 又产生了一个 " + prize + " 元大奖!");
                notifyAll();
                try {
                    wait();
                } catch (InterruptedException e) {
                    break;
                }
            }
        }
    }
}